﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Mahasiswa.WP.ViewModels;

namespace Mahasiswa.WP
{
    public partial class MahasiswaPage : PhoneApplicationPage
    {
        public MahasiswaPage()
        {
            InitializeComponent();
            LongListSelector_MainData_DataBind();
        }

        public async Task LongListSelector_MainData_DataBind()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync("http://169.254.80.80/akademik/api/Mahasiswa");
                response.EnsureSuccessStatusCode();
                
                if (response.IsSuccessStatusCode)
                {
                    var mhs = response.Content.ReadAsAsync<IEnumerable<MahasiswaModel>>().Result.ToList();
                    LongListSelector_MainData.ItemsSource = mhs;
                }
                else
                {
                    MessageBox.Show("Gagal");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ApplicationBarIconButton_Add_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MahasiswaAddPage.xaml", UriKind.Relative));
        }

        private void LongListSelector_MainData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (LongListSelector_MainData.SelectedItem == null)
            {
                return;
            }

            PhoneApplicationService.Current.State["objMahasiswa"] = LongListSelector_MainData.SelectedItem;
            NavigationService.Navigate(new Uri("/MahasiswaDetailPage.xaml", UriKind.Relative));

            LongListSelector_MainData.SelectedItem = null;
        }
    }
}